package com.yupi.yupicturespringboot.aop;


import com.yupi.yupicturespringboot.annotation.AuthCheck;
import com.yupi.yupicturespringboot.exception.BusinessException;
import com.yupi.yupicturespringboot.exception.ErrorCode;
import com.yupi.yupicturespringboot.model.entity.User;
import com.yupi.yupicturespringboot.model.enums.UserRoleEnum;
import com.yupi.yupicturespringboot.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;


    /**
     * 执行拦截
     *
     * @param joinPoint
     * @param authCheck
     * @return
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String mustRole = authCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
        //获取当前登录用户
        User loginUser = userService.getLoginUser(httpServletRequest);
        UserRoleEnum mustEnum = UserRoleEnum.getEnumByValue(mustRole);
        //如果不需要权限就放行
        if (mustEnum == null) {
            return joinPoint.proceed();
        }

        //必须有权限才通过
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(loginUser.getUserRole());
        if (userRoleEnum == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        //要求必须有管理员权限才放行，但用用户没有管理员权限
        if (userRoleEnum.ADMIN.equals(mustEnum) && !userRoleEnum.ADMIN.equals(userRoleEnum)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        //权限校验通过，放行
        return joinPoint.proceed();


    }
}
